package app

import (
	// "fmt"
	"time"
	// "encoding/json"
	// "io/ioutil"

	"github.com/go-apibox/api"
	"github.com/go-apibox/filter"
)

// 获取任务
// 总体任务状态

type RespTaskInfo struct {
	Name        string
	TotalCount  int // 总数
	DoneCount   int // 完成
	FailedCount int // 失败
	Retry       int ///
	StartTime   int
	DoneTime    int
}

type RespProductInfo struct {
	ProductId uint64
	*TaskLog
	// Addr         string
	// Account      string // 逛号
	// ProductCode  string
	// ProductTitle string
	// ReleaseTime  string
	// IsStart      string
	// HoldSec      int
}

type RespProductNext struct {
	TaskInfo *RespTaskInfo    // 任务信息
	Product  *RespProductInfo // 任务
}

// type MockDoneTaskInfo struct {
// 	ProductId uint32 // 必选
// 	ImgBase64 string // 可选
// 	ImgUrl    string // 可选
// }

// type MockReqProductGet struct {
// 	DeviceId  uint32
// 	DoneTasks []*MockDoneTaskInfo
// }

func ActionMockProductNext(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("DeviceId", filter.EmptyToNil(), filter.Required(), filter.Uint32())
	params.Add("ProductId", filter.EmptyToNil(), filter.Uint64())
	params.Add("ImgBase64", filter.EmptyToNil(), filter.String())
	params.Add("ImgUrl", filter.EmptyToNil(), filter.String())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}

	dId := params.GetUint32("DeviceId")
	pId := params.GetUint64("ProductId")

	app.logger.Debug(c.Request().PostForm.Encode())

	if pId != 0 {
		// 更新成功任务状态
		taslLog := &TaskLog{
			EndTime: time.Now().Unix(),
			Img:     params.GetString("ImgUrl"),
			Status:  TASK_STATUS_DONE,
		}

		if _, err := app.engine.Where("task_log_id=?", pId).Cols("end_time", "img", "status").Update(taslLog); err != nil {
			app.logger.Error(err)
			return c.Error.New(api.ErrorInvalidParam, "connect db faield")
		}
	}

	// 获取任务信息
	taskInfo := &RespTaskInfo{
		Name:        "task",
		TotalCount:  100,
		DoneCount:   12,
		FailedCount: 1,
		Retry:       3,
		StartTime:   123,
		DoneTime:    0,
	}
	resp := &RespProductNext{
		TaskInfo: taskInfo,
	}

	// 获取执行中的任务,
	// 如果存在, 判断发送次数, 超过设置任务失败,
	// 获取可用任务
	tl := new(TaskLog)
	has, err := app.engine.Where("device_id=?", dId).And("status=?", TASK_STATUS_DOING).Get(tl)
	if err != nil {
		app.logger.Error(err)
		return c.Error.New(api.ErrorInvalidParam, "connect db faield")
	}
	if has {
		if tl.SendCount < tl.Retry {
			tl.SendCount++
			if _, err := app.engine.Where("task_log_id=?", tl.TaskLogId).Cols("send_count").Update(tl); err != nil {
				app.logger.Error(err)
				return c.Error.New(api.ErrorInvalidParam, "connect db faield")
			}

			resp.Product = &RespProductInfo{
				TaskLog:   tl,
				ProductId: tl.TaskLogId,
			}

			return resp

		} else {
			// 更新状态
			tl.Status = TASK_STATUS_FAILED
			tl.EndTime = time.Now().Unix()
			if _, err := app.engine.Where("task_log_id=?", tl.TaskLogId).Cols("status", "end_time").Update(tl); err != nil {
				app.logger.Error(err)
			}
		}

	}

	// 获取未执行任务, 按执行时间排序
	tl = new(TaskLog)
	has, err = app.engine.Where("device_id=?", dId).And("status=?", TASK_STATUS_UNDO).And("appointment_time < ?", time.Now().Unix()).Asc("appointment_time").Get(tl)
	if err != nil {
		app.logger.Error(err)
		return c.Error.New(api.ErrorInvalidParam, "connect db faield")
	}
	if !has {
		time.Sleep(time.Second * 10)
		return resp
	}
	if tl.StopTime < time.Now().Unix() {
		tl.Status = TASK_STATUS_TIMEOUT
		tl.EndTime = time.Now().Unix()
		app.engine.Where("stop_time < ? ", time.Now().Unix()).Cols("status", "end_time").Update(tl)
		time.Sleep(time.Second * 10)
		return resp
	}
	//  更新任务转
	tl.SendCount++
	tl.Status = TASK_STATUS_DOING
	tl.StartTime = time.Now().Unix()
	if _, err := app.engine.Where("task_log_id=?", tl.TaskLogId).Cols("send_count", "status", "start_time").Update(tl); err != nil {
		app.logger.Error(err)
		return c.Error.New(api.ErrorInvalidParam, "connect db faield")
	}

	resp.Product = &RespProductInfo{
		TaskLog:   tl,
		ProductId: tl.TaskLogId,
	}
	return resp

	// if time.Now().Second()%2 == 0 {
	// 	time.Sleep(time.Second * 10)
	// 	resp := &MockRespProductGet{
	// 		TaskInfo: &MockTask{
	// 			Name:        "mock task",
	// 			TotalCount:  0,
	// 			DoneCount:   0,
	// 			FailedCount: 0,
	// 			Retry:       3,
	// 			StartTime:   123,
	// 			DoneTime:    0,
	// 		},
	// 	}

	// 	return resp
	// }

	// resp := &MockRespProductGet{
	// 	TaskInfo: &MockTask{
	// 		Name:        "mock task",
	// 		TotalCount:  100,
	// 		DoneCount:   12,
	// 		FailedCount: 1,
	// 		Retry:       3,
	// 		StartTime:   123,
	// 		DoneTime:    0,
	// 	},
	// 	// Product: &MockProduct{
	// 	// 	ProductId:    234,
	// 	// 	Addr:         "https://market.m.taobao.com/app/tb-source-app/video-fullpage/pages/index2?wh_weex=false&wx_navbar_hidden=true&wx_navbar_transparent=true&type=guangguang&source=guangguang&id=419443840476",
	// 	// 	Account:      "番茄炒蛋蛋蛋黄派1",
	// 	// 	ProductCode:  "420150986584",
	// 	// 	ProductTitle: "虾仁黑木耳炒百合怎么炒好吃",
	// 	// 	ReleaseTime:  "14",
	// 	// 	IsStart:      "",
	// 	// 	HoldSec:      5,
	// 	// },
	// }

	return resp

}
